import 'package:bloc/bloc.dart';
import 'package:dio/dio.dart';
import 'package:f_demo/bloc/index.dart';
import 'package:f_demo/commons/index.dart';
import 'package:f_demo/models/index.dart';
import 'package:f_demo/utils/index.dart';

class OauthBloc extends Bloc<OauthEvent, OauthState> {
  @override
  OauthState get initialState => OauthLoginInitialState();

  @override
  Stream<OauthState> mapEventToState(OauthEvent event) async* {
    if (event is OauthLoginEvent) {
      yield OauthLoginLoadingState();
      yield await login(event);
      return;
    }
  }

  Future<OauthState> login(OauthLoginEvent event) async {
    OauthState oauthState;
    LoginRequest loginRequest = LoginRequest(username: event.username, password: event.password);

    try {
      Response response = await Http.post(ApiPath.login, param: loginRequest.toJson());
      oauthState = OauthLoginSuccessState();
      LoginResponse loginResponse = LoginResponse.fromJson(response.data);
    } on DioError catch (err) {
      oauthState = OauthLoginFailureState(errorMessage: err.response.data['message']);
    }
    return oauthState;
  }
}
